package com.example.myandroiduseflutter

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.example.myandroiduseflutter.databinding.ActivityMainBinding
import com.idlefish.flutterboost.containers.FlutterBoostFragment

import io.flutter.embedding.android.FlutterFragment
import io.flutter.embedding.android.FlutterView


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityMainBinding = DataBindingUtil.setContentView(
            this, R.layout.activity_main
        )




        binding.tvAndroid.tag = AndroidFragment::class.java.name
        binding.tvFlutter.tag = CustomFlutterBoostFragment::class.java.name
        //



        showFragment(binding.tvAndroid)

        binding.tvAndroid.setOnClickListener {
            showFragment(binding.tvAndroid)
            hideFragment(binding.tvFlutter)
        }

        binding.tvFlutter.setOnClickListener {
            showFragment(binding.tvFlutter)
            hideFragment(binding.tvAndroid)
        }
    }


    private fun showFragment(curView: View) {
        val fragmentManager: FragmentManager = supportFragmentManager
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        val tag = curView.tag as String
        var fragment: Fragment? = fragmentManager.findFragmentByTag(tag)
        if (fragment == null) {
            val factory: FragmentFactory = fragmentManager.fragmentFactory
            fragment = factory.instantiate(classLoader, tag)
            fragmentTransaction.add(R.id.fl_container, fragment, tag)
            fragmentTransaction.commitAllowingStateLoss()
        } else {
            val isHide: Boolean = fragment.isHidden
            if (isHide) {
                fragmentTransaction.show(fragment)
                fragmentTransaction.commitAllowingStateLoss()
                fragment.onResume() //切换Fragment，实时刷新数据
            }
        }
    }


    private fun hideFragment(lastView: View) {
        val fragmentManager: FragmentManager = supportFragmentManager
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        val tag = lastView.tag as String
        fragmentManager.findFragmentByTag(tag)?.let {
            val isHide: Boolean = it.isHidden
            if (!isHide) {
                fragmentTransaction.hide(it)
                fragmentTransaction.commitAllowingStateLoss()
            }
        }
    }
}